import * as echarts from '../../ec-canvas/echarts';

const app = getApp();
var mqtt = require('../../utils/mqtt.js');
var temp=0; 
var hum=0; 
function initChart_temp(canvas, width, height, dpr) {
  
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {
    backgroundColor: "#ffffff",
    series: [{
      name: '温度',
      type: 'gauge',
      detail: {
        formatter: '{value}'
      },
      axisLine: {
        show: true
      },
      data: [{
        value: 0,
        name: '温度(℃)',
      }]

    }]
  };
  setInterval(function() {
    option.series[0].data[0].value = temp;
    chart.setOption(option, true);
  }, 500)
  chart.setOption(option, true);

  return chart;
}
function initChart_hum(canvas, width, height, dpr) {
    const chart = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr // new
    });
    canvas.setChart(chart);
  
    var option = {
      backgroundColor: "#ffffff",
      series: [{
        name: '湿度',
        type: 'gauge',
        detail: {
          formatter: '{value}'
        },
        axisLine: {
          show: true
        },
        data: [{
          value: 0,
          name: '湿度(%)',
        }]
  
      }]
    };
    setInterval(function() {
      option.series[0].data[0].value = hum;
      chart.setOption(option, true);
    }, 500)
    chart.setOption(option, true);
  
    return chart;
  }
Page({
  onShareAppMessage: function (res) {
    return {
      title: 'ECharts 可以在微信小程序中使用啦！',
      path: '/pages/index/index',
      success: function () { },
      fail: function () { }
    }
  },
  data: {
    topic:"ZUCC-HJX/esp",
    button_type:'primary',
    sub_text:'订阅',
    sub_state:false,
    ec_temp: {
      onInit: initChart_temp
    },
    ec_hum: {
        onInit: initChart_hum
      }
  },

  onReady() {
  },
  TopicInput:function(e){
    this.setData({
      topic:e.detail.value
    })
  },
  mqttsub: function() {
    var that=this;
    if(this.data.sub_state == true){
      app.globalData.client.unsubscribe(this.data.topic)
      that.setData({
        button_type:'primary',
        sub_text:'订阅',
        sub_state:false
      })
      return;
    }
    app.globalData.client.subscribe(this.data.topic);
    that.setData({
      button_type:'warn',
      sub_text:'取消订阅',
      sub_state:true
    })
    app.globalData.client.on('message', function(topic, payload) { 
      temp=JSON.parse(payload).temp;
      hum=JSON.parse(payload).hum;
      // that.setData({
      //    msg:"温度:"+JSON.parse(payload).temp+" 湿度:"+JSON.parse(payload).hum+ '<br>' + that.data.msg 
      //    //msg:payload+ '<br>' + that.data.msg 

        
      // })
    })
  },
  onLoad: function() {
    setInterval(function() {
      temp=temp;
      hum=hum;
    }, 500)
  }
});


